package com.sky.service.impl;

import com.sky.controller.admin.WorkSpaceController;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService{
    @Autowired
    private ReportMapper reportMapper;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO reportTurnover(LocalDate begin, LocalDate end) {
        List<LocalDate> localDataList = new ArrayList<>();
        localDataList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            localDataList.add(begin);
        }
        String dateList = StringUtils.join(localDataList, ",");
        List<Double> amountList = new ArrayList<>();
        //接着要把营业额度查出来 首先要遍历每一天 然后获取这个日期对应的营业额
        for (LocalDate localDate : localDataList) {
            //获取当天的最早时间  加上时分秒
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            //获取当天的最晚时间
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //select sum(amount) from orders where order_time >= beginTime and order_time <= endTime
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double totalMoney = reportMapper.getTurnover(map);
            totalMoney = totalMoney == null ? 0.0 : totalMoney;
            amountList.add(totalMoney);
        }

        String turnoverList = StringUtils.join(amountList, ",");
        return TurnoverReportVO.builder().dateList(dateList).
                turnoverList(turnoverList).
                build();
    }

    @Override
    public UserReportVO reportUser(LocalDate begin, LocalDate end) {
        List<LocalDate> localDataList = new ArrayList<>();
        localDataList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            localDataList.add(begin);
        }
        String dateList = StringUtils.join(localDataList, ",");
        List<Integer> userTotalList = new ArrayList<>();
        List<Integer> userNewList = new ArrayList<>();
        for (LocalDate localDate : localDataList) { //遍历每一天
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end", endTime);
            //截止今天的总用户数量
            Integer userTotal = reportMapper.getUserSta(map);
            userTotal = userTotal == null ? 0 : userTotal;
            userTotalList.add(userTotal);
            //今天的新增用户数量
            map.put("begin", beginTime);
            Integer userNew = reportMapper.getUserSta(map);
            userNew = userNew == null ? 0 : userNew;
            userNewList.add(userNew);
        }
        String totalUserList = StringUtils.join(userTotalList, ",");
        String newUserList = StringUtils.join(userNewList, ",");
        return UserReportVO.builder().dateList(dateList).
                totalUserList(totalUserList).
                newUserList(newUserList).
                build();
    }

    @Override
    public OrderReportVO reportOrders(LocalDate begin, LocalDate end) {
        List<LocalDate> localDataList = new ArrayList<>();
        localDataList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            localDataList.add(begin);
        }
        String dateList = StringUtils.join(localDataList, ",");
        //每日订单数 每日有效订单数
        List<Integer> CountList = new ArrayList<>();
        List<Integer> validCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        for (LocalDate localDate : localDataList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            //计算每天的订单数量
            Integer orderCount = reportMapper.getOrderCount(map);
            orderCount = orderCount == null ? 0 : orderCount;
            CountList.add(orderCount);
            totalOrderCount += orderCount; //累加订单数量
            map.put("status", Orders.COMPLETED);

            //计算每天的有效订单数
            Integer validOrderCountday = reportMapper.getOrderCount(map);
            validOrderCountday = validOrderCountday == null ? 0 : validOrderCountday;
            validCountList.add(validOrderCountday);
            validOrderCount += validOrderCountday;//累加有效订单数
        }
        String orderCountList = StringUtils.join(CountList, ",");
        String validOrderCountList = StringUtils.join(validCountList, ",");
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }



        return OrderReportVO.builder().dateList(dateList).
                orderCountList(orderCountList).
                validOrderCountList(validOrderCountList).
                totalOrderCount(totalOrderCount).validOrderCount(validOrderCount).
                orderCompletionRate(orderCompletionRate).build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", Orders.COMPLETED);
        List<GoodsSalesDTO> salesTop10 = reportMapper.getSalesTop10(map);
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        String nameList = StringUtils.join(names, ",");
        String numberList = StringUtils.join(numbers, ",");
        return SalesTop10ReportVO.builder().nameList(nameList).
                numberList(numberList).
                build();
    }

    @Override
    public void export(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //获取营业额度
        Map map = new HashMap();
        map.put("begin", LocalDateTime.of(begin,LocalTime.MIN));
        map.put("end", LocalDateTime.of(end,LocalTime.MAX));
        map.put("status", Orders.COMPLETED);
        Double turnover = reportMapper.getTurnover(map);//营业额
        turnover = turnover == null ? 0.0 : turnover;

        Integer validOrderCount = reportMapper.getOrderCount(map);//有效订单数
        validOrderCount = validOrderCount == null ? 0 : validOrderCount;

        Integer newUsers = reportMapper.getUserSta(map);//新增用户数
        newUsers = newUsers == null ? 0 : newUsers;

        Double unitPrice = reportMapper.getAvgPrice(map);//平均单价
        unitPrice = unitPrice == null ? 0.0 : unitPrice;

        map.put("status",null);
        Integer orderCount = reportMapper.getOrderCount(map);//订单总数
        orderCount = orderCount == null ? 0 : orderCount;

        Double orderCompletionRate = 0.0;
        if(orderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / orderCount;
        }
        BusinessDataVO data = BusinessDataVO.builder().turnover(turnover).validOrderCount(validOrderCount).
                newUsers(newUsers).unitPrice(unitPrice).
                orderCompletionRate(orderCompletionRate).build();

        InputStream xlsx = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //将数据填充到模板中
        //获取sheet1
        try {
            //填入概览数据
            XSSFWorkbook workbook = new XSSFWorkbook(xlsx);
            XSSFSheet sheet = workbook.getSheetAt(0);
            sheet.getRow(1).getCell(1).setCellValue("时间:" + begin + "至" + end + "营业数据");
            sheet.getRow(3).getCell(2).setCellValue(data.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(data.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(data.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(data.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(data.getUnitPrice());
            //填入明细数据
            LocalDate time = begin;
            int i = 0;
            while(i < 30){
                sheet.getRow(7 + i).getCell(1).setCellValue(time.toString());
                //这里代码逻辑可以复用的 懒得改了
                LocalDateTime beginTime = LocalDateTime.of(time, LocalTime.MIN);
                LocalDateTime endTime = LocalDateTime.of(time, LocalTime.MAX);
                Map map1 = new HashMap();
                map1.put("begin", beginTime);
                map1.put("end", endTime);
                map1.put("status", Orders.COMPLETED);
                turnover = reportMapper.getTurnover(map1);//营业额
                turnover = turnover == null ? 0.0 : turnover;

                validOrderCount = reportMapper.getOrderCount(map1);//有效订单数
                validOrderCount = validOrderCount == null ? 0 : validOrderCount;

                newUsers = reportMapper.getUserSta(map1);//新增用户数
                newUsers = newUsers == null ? 0 : newUsers;

                unitPrice = reportMapper.getAvgPrice(map1);//平均单价
                unitPrice = unitPrice == null ? 0.0 : unitPrice;


                map1.put("status",null);
                orderCount = reportMapper.getOrderCount(map1);//订单总数
                orderCount = orderCount == null ? 0 : orderCount;

                orderCompletionRate = 0.0;
                if(orderCount != 0){
                    orderCompletionRate = validOrderCount.doubleValue() / orderCount;
                }
                BusinessDataVO data1 = BusinessDataVO.builder().turnover(turnover).validOrderCount(validOrderCount).
                        newUsers(newUsers).unitPrice(unitPrice).
                        orderCompletionRate(orderCompletionRate).build();
                sheet.getRow( 7 + i).getCell(2).setCellValue(data1.getTurnover());
                sheet.getRow( 7 + i).getCell(3).setCellValue(data1.getValidOrderCount());
                sheet.getRow( 7 + i).getCell(4).setCellValue(data1.getOrderCompletionRate());
                sheet.getRow( 7 + i).getCell(5).setCellValue(data1.getUnitPrice());
                sheet.getRow( 7 + i).getCell(6).setCellValue(data1.getNewUsers());
                time = time.plusDays(1);
                i++;
            }
            //将文件输出到浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
